package org.sample.mqtt.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import org.sample.mqtt.component.model.MqttResponse;
import org.sample.mqtt.model.toclient.SettingUpdate;
import org.sample.mqtt.model.toserver.CommonResponse;
import org.sample.mqtt.model.toserver.Location;
import org.sample.mqtt.service.MessageService;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;

@RestController
@RequestMapping(path = "mqtt")
public class MqttController {

    @Resource
    private MessageService messageService;

    @Operation(summary = "发送同步消息")
    @PostMapping("send")
    public CompletableFuture<MqttResponse> sendMessage(@Parameter(description = "设备ID") @RequestParam(defaultValue = "test123") String deviceId,
                                                       @Parameter(description = "模拟应答") @RequestParam(defaultValue = "true") boolean mock,
                                                       @RequestBody SettingUpdate settingUpdate) {
        if (mock)
            new Thread(() -> {
                try {
                    Thread.sleep(200);
                    messageService.notify(deviceId, new CommonResponse(settingUpdate.getSerialNo(), deviceId, ThreadLocalRandom.current().nextInt()));

                } catch (InterruptedException e) {
                }
            }).start();

        CompletableFuture<MqttResponse> result = messageService.request(deviceId, settingUpdate);
        result.thenAccept(response -> {
            //TODO 处理设备应答业务逻辑
            System.out.println(response);
        });
        return result.exceptionally(throwable -> new CommonResponse());
    }

    @Operation(summary = "发送通知消息（无返回报文）")
    @PostMapping("send/notice")
    public void sendNotice(@Parameter(description = "设备ID") @RequestParam(defaultValue = "test123") String deviceId,
                           @RequestBody Location location) {
        messageService.notify(deviceId, location);
    }
}